package com.taobao.ued.toy.web;

import com.taobao.cms.biz.ao.PhotoAO;
import com.taobao.session.SessionKeyConstants;
import com.taobao.ued.toy.domain.Designer;
import com.taobao.ued.toy.domain.FollowRelation;
import com.taobao.ued.toy.domain.ToyConfig;
import com.taobao.ued.toy.service.ToyManager;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class DesignerController {


	@Resource
	private PhotoAO photoAO;

	private int followerPageCount = 40;

	@Autowired
	private ToyManager toyManager;

	@Resource
	private ToyConfig toyConfig;


	@RequestMapping("/{domain}")
	public String personal(@PathVariable String domain,
						   HttpServletRequest request,
						   HttpServletResponse response,
						   Model model) throws Exception {

		int followingPageCount = toyConfig.getFollowingPageCount();
		Designer d = toyManager.getDesignerByDomain(domain);
		if (d.getId() == null) {
			response.sendRedirect("http://" + request.getServerName() +
					request.getContextPath() + "/secure/active");
			return null;
		}
		String id = d.getId();
		d.setFollowings(toyManager.getFollowings(id, 0, followingPageCount));
		d.setFollowingsCount(toyManager.getFollowingsCount(id));
		d.setNotAckFollowersCount(toyManager.getNotAckFollowersCount(id));
		int totalPage = d.getFollowingsCount() / followingPageCount;
		if (d.getFollowingsCount() % followingPageCount != 0) {
			totalPage++;
		}
		model.addAttribute("designer", d);
		model.addAttribute("contextpath", request.getContextPath());
		model.addAttribute("totalPage", totalPage);
		return "personal";
	}

	@RequestMapping("/{domain}/followings")
	public String followings(@PathVariable String domain,
							 @RequestParam(required = false, value = "page") Integer pageObj,
							 Model model) throws Exception {
		Designer d = toyManager.getDesignerByDomain(domain);
		String id = d.getId();
		int page = 0;
		if (pageObj != null) {
			page = pageObj - 1;
		}
		int followingPageCount = toyConfig.getFollowingPageCount();
		List<Designer> ds = toyManager.getFollowings(id, page * followingPageCount,
				(page + 1) * followingPageCount);
		int followingsCount = toyManager.getFollowingsCount(id);
		int totalPage = followingsCount / followingPageCount;
		if (followingsCount % followingPageCount != 0) {
			totalPage++;
		}
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("followings", ds);
		return "followings";
	}


	@RequestMapping("/secure/followings/add/{followingId}")
	public String addFollowing(
			HttpSession session,
			HttpServletRequest request,
			HttpServletResponse response,
			@PathVariable String followingId) throws Exception {

		String id = (String) session.getAttribute(SessionKeyConstants.ATTRIBUTE_USER_ID);
		if (id == null) {
			response.sendRedirect(toyConfig.getLoginUrl() + URLEncoder.encode("http://" + request.getServerName() +
					request.getContextPath() + "/secure/followings/add/" + followingId));
			return null;
		}
		FollowRelation fr = new FollowRelation();
		fr.setDesignerId(id);
		fr.setFollowingId(followingId);
		toyManager.addFollowRelation(fr);
		return "success";
	}

	@RequestMapping("/secure//followings/delete/{followingId}")
	public String deleteFollowing(HttpSession session,
								  HttpServletRequest request,
								  HttpServletResponse response,
								  @PathVariable String followingId) throws Exception {
		String id = (String) session.getAttribute(SessionKeyConstants.ATTRIBUTE_USER_ID);
		if (id == null) {
			response.sendRedirect(toyConfig.getLoginUrl() + URLEncoder.encode("http://" + request.getServerName() +
					request.getContextPath() + "/secure//followings/delete/" + followingId));
			return null;
		}
		FollowRelation fr = new FollowRelation();
		fr.setDesignerId(id);
		fr.setFollowingId(followingId);
		toyManager.deleteFollowRelation(fr);
		return "success";
	}

	@RequestMapping("/secure/followers/acks")
	public String notAckFollowers(HttpSession session,
								  HttpServletRequest request,
								  HttpServletResponse response,
								  Model model) throws Exception {

		String id = (String) session.getAttribute(SessionKeyConstants.ATTRIBUTE_USER_ID);

		if (id == null) {
			response.sendRedirect(toyConfig.getLoginUrl() + URLEncoder.encode("http://" + request.getServerName() +
					request.getContextPath() + "/secure/followers/acks"));
			return null;
		}
		Designer d = toyManager.getDesigner(id);
		int followingPageCount = toyConfig.getFollowingPageCount();
		d.setFollowings(toyManager.getFollowings(id, 0, followingPageCount));
		d.setFollowingsCount(toyManager.getFollowingsCount(id));
		d.setNotAckFollowersCount(toyManager.getNotAckFollowersCount(id));
		int totalPage = d.getFollowingsCount() / followingPageCount;
		if (d.getFollowingsCount() % followingPageCount != 0) {
			totalPage++;
		}
		List<Designer> ds = toyManager.getNotAckFollowers(id, 0, followerPageCount);
		d.setNotAckFollowers(ds);
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("followers", ds);
		model.addAttribute("designer", d);
		return "follower_acks";
	}

	@RequestMapping("/{domain}/followers")
	public String followers(@PathVariable String domain,
							@RequestParam(required = false, value = "page") Integer pageObj,
							Model model) throws Exception {

		Designer d = toyManager.getDesignerByDomain(domain);
		String id = d.getId();
		int page = 0;
		if (pageObj != null) {
			page = pageObj - 1;
		}
		List<Designer> ds = toyManager.getFollowers(id, page * followerPageCount,
				(page + 1) * followerPageCount);
		int followersCount = toyManager.getFollowersCount(id);
		int totalPage = followersCount / followerPageCount;
		if (followersCount % followerPageCount != 0) {
			totalPage++;
		}
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("followers", ds);
		return "followers";
	}

	@RequestMapping("/secure/followers/ack/{designerId}")
	public String ackFollowing(@PathVariable String designerId,
							   HttpSession session,
							   HttpServletRequest request,
							   HttpServletResponse response,
							   Model model) throws Exception {
		String id = (String) session.getAttribute(SessionKeyConstants.ATTRIBUTE_USER_ID);

		if (id == null) {
			response.sendRedirect(toyConfig.getLoginUrl() + URLEncoder.encode("http://" + request.getServerName() +
					request.getContextPath() + "/secure/followers/ack/" + designerId));
			return null;
		}
		FollowRelation fr = new FollowRelation();
		fr.setDesignerId(designerId);
		fr.setFollowingId(id);
		toyManager.acknowledgement(fr);
		return "success";
	}

	@RequestMapping("/secure/active")
	public String updateInfo(HttpServletRequest request,
							 HttpSession session,
							 HttpServletResponse response,
							 Model model) throws Exception {
		String id = (String) session.getAttribute(SessionKeyConstants.ATTRIBUTE_USER_ID);
		if (id == null) {
			response.sendRedirect(toyConfig.getLoginUrl() + URLEncoder.encode("http://" + request.getServerName() +
					request.getContextPath() + "/secure/active"));
			return null;
		}
		Designer d = toyManager.getDesigner(id);
		model.addAttribute("contextpath", request.getContextPath());
		model.addAttribute("designer", d);
		return "info";
	}

	@RequestMapping(value = "/secure/doActive", method = RequestMethod.POST)
	public String updateInfo(
			@ModelAttribute Designer designer,
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "avatarFile")
			MultipartFile avatarFile,
			HttpSession session,
			Model model
	) throws Exception {
		String id = (String) session.getAttribute(SessionKeyConstants.ATTRIBUTE_USER_ID);

		if (id == null) {
			response.sendRedirect(toyConfig.getLoginUrl() + URLEncoder.encode("http://" + request.getServerName() +
					request.getContextPath() + "/secure/active"));
			return null;
		}

		designer.setId(id);
		designer.setName((String) session.getAttribute(SessionKeyConstants.ATTRIBUTE_NICK));

		Designer domainDesigner = toyManager.getDesignerByDomain(designer.getDomain());

		model.addAttribute("contextpath", request.getContextPath());
		model.addAttribute("designer", designer);

		if (domainDesigner.getId() != null && !domainDesigner.getId().equals(id)) {
			model.addAttribute("error", "独立域名已经占用");
			return "info";
		}

		if (avatarFile.getSize() != 0) {
			String json = photoAO.upladFile(designer.getName(),
					avatarFile.getOriginalFilename(), avatarFile.getContentType(),
					avatarFile.getBytes());
			JSONObject jsonObject = JSONObject.fromObject(json);
			designer.setAvatar((String) jsonObject.get("url"));
		}
		toyManager.updateDesigner(designer);

		response.sendRedirect(request.getContextPath() + "/" + designer.getDomain());
		return null;
	}
}
